package nsq

import (
	"fmt"

	"github.com/golang/glog"
	nsq "github.com/nsqio/go-nsq"
)

// PublisherEnv nsq publisher init params
type PublisherEnv struct {
	Address string
	Config  *nsq.Config
}

// Message nsq message publish object
type Message struct {
	Topic   string
	Content []byte
}

// Publisher producer publish interface
type Publisher interface {
	Init(*PublisherEnv) error // init function
	Publish(*Message) error   // publish function
}

type publish struct {
	producer *nsq.Producer
}

// NewPublish publisher new function
func NewPublish() Publisher {
	return new(publish)
}

func (p *publish) Init(env *PublisherEnv) error {
	producer, err := nsq.NewProducer(env.Address, env.Config) // init producer
	if err != nil {
		glog.Fatalf("nsq connect fail: %v", err)
	} else {
		p.producer = producer
	}
	return err
}

func (p *publish) Publish(message *Message) error {
	if p.producer != nil {
		if message == nil || message.Topic == "" || len(message.Content) == 0 { // check if message is valid
			return fmt.Errorf("message object is nil or message topic is nil or message content is nil")
		}
		err := p.producer.Publish(message.Topic, message.Content) // send message
		return err
	}
	return fmt.Errorf("producer is nil")
}
